package ppu

import "github.com/imacks/bitflags-go"

const (
	SNotused        = 0b00000001
	SNotused2       = 0b00000010
	SNotused3       = 0b00000100
	SNotused4       = 0b00001000
	SNotused5       = 0b00010000
	SSpriteOverflow = 0b00100000
	SpriteZeroHit   = 0b01000000
	SVblankStarted  = 0b10000000
)

type StatusRegister struct {
	Bits byte
}

// NewStatusRegister creates a new status register
func NewStatusRegister() *StatusRegister {
	return &StatusRegister{
		Bits: 0,
	}
}

// SetVblankStatus sets the vblank status bit
func (s *StatusRegister) SetVblankStatus(status bool) {
	if status {
		s.Bits = bitflags.Set(s.Bits, SVblankStarted)
	} else {
		s.Bits = bitflags.Del(s.Bits, SVblankStarted)
	}
}

// SetSpriteZeroHit sets the sprite zero hit status bit
func (s *StatusRegister) SetSpriteZeroHit(status bool) {
	if status {
		s.Bits = bitflags.Set(s.Bits, SpriteZeroHit)
	} else {
		s.Bits = bitflags.Del(s.Bits, SpriteZeroHit)
	}
}

// SetSpriteOverflow sets the sprite overflow status bit
func (s *StatusRegister) SetSpriteOverflow(status bool) {
	if status {
		s.Bits = bitflags.Set(s.Bits, SSpriteOverflow)
	} else {
		s.Bits = bitflags.Del(s.Bits, SSpriteOverflow)
	}
}

// ResetVblankStatus resets the vblank status bit
func (s *StatusRegister) ResetVblankStatus() {
	s.Bits = bitflags.Del(s.Bits, SVblankStarted)
}

// IsInVblank returns true if the vblank status bit is set
func (s *StatusRegister) IsInVblank() bool {
	return bitflags.Has(s.Bits, SVblankStarted)
}

// Snapshot returns the current status register value
func (s *StatusRegister) Snapshot() byte {
	return s.Bits
}
